# coding: utf-8
from PySide6.QtCore import Qt, QUrl, QTimer, QRegularExpression
from PySide6.QtGui import QRegularExpressionValidator
from PySide6.QtWidgets import QVBoxLayout, QWidget, QLineEdit, QHBoxLayout
from qeventmanager import qevent_manager
from qfluentwidgets import LineEdit, Action, FluentIcon as FIF, PrimaryPushButton, CheckBox, HyperlinkLabel, BodyLabel

from api import LoginAPI, LoginCodeAPI
from common import cfg, signalBus
from components import Alert


class UICaptchaLoginWidget:
    """
    验证码登录组件 UI 实现
    """

    def setupUi(self):
        """
        初始化 UI 组件
        """
        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout_2 = QHBoxLayout()
        self.photoLineEdit = LineEdit(self)
        self.captchaLineEdit = LineEdit(self)
        self.getCaptchaButton = PrimaryPushButton("获取验证码", self)
        self.checkBox = CheckBox("阅读并同意", self)
        self.userBtn = HyperlinkLabel(QUrl('https://service.qsxt.info/qsxt_yhxy.html'), "<用户协议>", self)
        self.separationLabel = BodyLabel("和", self)
        self.privacyBtn = HyperlinkLabel(QUrl('https://service.qsxt.info/qsxt_yszc.html'), "<隐私政策>", self)
        self.loginButton = PrimaryPushButton("登录", self)

        self.photoLineEdit.addAction(Action(FIF.PHONE, "", self.photoLineEdit),
                                     QLineEdit.ActionPosition.LeadingPosition)
        self.captchaLineEdit.addAction(Action(FIF.VPN, "", self.captchaLineEdit),
                                       QLineEdit.ActionPosition.LeadingPosition)

        self.photoLineEdit.setPlaceholderText("手机号")
        self.captchaLineEdit.setPlaceholderText("验证码")
        self.captchaLineEdit.setMaxLength(6)
        self.photoLineEdit.setFixedHeight(40)
        self.captchaLineEdit.setFixedHeight(40)
        self.getCaptchaButton.setFixedHeight(40)

        self.photoLineEdit.setClearButtonEnabled(True)
        self.captchaLineEdit.setClearButtonEnabled(True)
        self.checkBox.setChecked(True)

        self.photoLineEdit.setValidator(QRegularExpressionValidator(QRegularExpression("[0-9]{11}")))

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setSpacing(20)
        self.verticalLayout.addWidget(self.photoLineEdit)

        self.horizontalLayout.addWidget(self.captchaLineEdit)
        self.horizontalLayout.addWidget(self.getCaptchaButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.horizontalLayout_2.setSpacing(5)
        self.horizontalLayout_2.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout_2.addWidget(self.checkBox)
        self.horizontalLayout_2.addWidget(self.userBtn)
        self.horizontalLayout_2.addWidget(self.separationLabel)
        self.horizontalLayout_2.addWidget(self.privacyBtn)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

        self.verticalLayout.addWidget(self.loginButton)
        self.verticalLayout.addStretch(1)


class CaptchaLoginWidget(QWidget, UICaptchaLoginWidget):
    """
    验证码登录组件
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
        self.timer = QTimer(self)
        self.index = 0
        self.sessionId = ''

        if cfg.get(cfg.phoneNumber):
            self.photoLineEdit.setText(cfg.get(cfg.phoneNumber))

        self.loginButton.clicked.connect(self.onLoginButtonClicked)
        self.getCaptchaButton.clicked.connect(self.onGetCaptchaButtonClicked)
        self.timer.timeout.connect(self.onTimerTimeout)
        self.timer.setInterval(1000)  # 1分钟

    def onTimerTimeout(self):
        """
        验证码定时器超时事件
        :return:
        """
        if self.index == 60:
            self.getCaptchaButton.setEnabled(True)
            self.getCaptchaButton.setText("获取验证码")
            self.timer.stop()
        else:
            self.getCaptchaButton.setText(f"{self.index} 秒后重试")
            self.index += 1

    def onLoginButtonClicked(self):
        """
        登录按钮点击事件
        """
        photo = self.photoLineEdit.text()
        captcha = self.captchaLineEdit.text()
        if not photo or not captcha:
            Alert.warning("请填写手机号和验证码")
            return
        if not self.checkBox.isChecked():
            Alert.warning("请阅读并同意用户协议和隐私政策")
            return
        cfg.set(cfg.phoneNumber, photo)
        # 登录逻辑
        qevent_manager.addTask(LoginAPI.loginByAuthCode, photo, captcha, self.sessionId, slot=self.onLoginResponse)

    def onLoginResponse(self, result: dict):
        """
        登录响应回调
        :param result:
        :return:
        """
        hr = result.get('hr')
        message = result.get('message')

        if hr == 0:
            Alert.success('登录成功')
            signalBus.loginSuccessSignal.emit()
            return
        else:
            Alert.error(message)

    def onGetCaptchaButtonClicked(self):
        """
        获取验证码按钮点击事件
        :return:
        """
        photo = self.photoLineEdit.text()
        if not photo:
            Alert.warning("请填写手机号")
            return
        if len(photo) != 11:
            Alert.warning("手机号格式不正确")
            return
        qevent_manager.addTask(LoginCodeAPI.getValidationCode, photo, 1, slot=self.onGetCaptchaResponse)

    def onGetCaptchaResponse(self, result: dict):
        """
        获取验证码响应回调
        :param result:
        :return:
        """
        data = result.get('data')
        hr = result.get('hr')
        message = result.get('message')
        if hr != 0:
            Alert.error(message)
            return
        else:
            Alert.success('验证码已发送，请注意查收')
        self.sessionId = data.get('sessionId')
        self.getCaptchaButton.setEnabled(False)
        self.index = 0
        self.timer.start()
